package com.example.Servlet;

import com.example.Service.UserService;
import com.google.gson.Gson;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@WebServlet(name = "deleteBatchUser", value = "/deleteBatchUser")
public class deleteBatchUser extends HttpServlet {
    private String message;

    public void init() {
        message = "Hello World!";
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
//        response.setContentType("text/html");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        super.doPost(req, resp);
        BufferedReader br = new BufferedReader(req.getReader());
        StringBuffer sbuffer = new StringBuffer();
        String s = "";
        while ((s = br.readLine()) != null) {              //按行读
            sbuffer.append(s);
        }
        System.out.println(sbuffer.toString());     //前端传过来的json数据

        //JSon解析  后端向前端发送，toJson   前端向后端发送整合  json 字符串--->Java对象
        Gson gson = new Gson();
        Map<String,Object>userIds= gson.fromJson(sbuffer.toString(), Map.class);
        ArrayList<Double> list = (ArrayList<Double>) userIds.get("ids");
        List<Integer> integerList = list.stream()
                // 将每个Double转换为Integer（先转int再装箱）
                .map(d -> d.intValue()) // 或使用 (d -> (int) d.doubleValue())
                .collect(Collectors.toList());

        UserService userService = new UserService();//调用业务方法实现登录功能
        int flag=userService.deleteBatchUser(integerList);
        Map<String,Object> map=new HashMap<>();
        //接口规范  成功code=200 msg="登录成功",失败code=500，失败原因描述清楚：账号或密码错误
        if (flag>0) {
            map.put("code", 200);
            map.put("msg", "删除成功");
        } else {
            map.put("code", 500);
            map.put("msg", "删除失败");
        }
        //向前端发送响应json数据  集合对象--->JSON字符串
        //toJson--->把对象或集合转换成json数据   fromJson--->把json数据转换成对象或集合
        String json = gson.toJson(map);
        resp.getWriter().write(json);
    }
    public void destroy() {
    }
}